import os
import time

from fastapi import APIRouter, Depends, File, Form, Request, UploadFile
from starlette.responses import HTMLResponse
from tortoise.transactions import atomic

from applications import settings
from applications.common.render_template import templates
from applications.common.user_manager import permission_depends
from applications.utils.http import fail_api, success_api, table_api, PageResponse, ResultResponse
from applications.models import Photo
from applications.models.admin_photo import PhotoSchema

route = APIRouter(prefix="/file", tags=["系统管理-图片管理"])


#  图片管理
@route.get(
    "/",
    dependencies=[Depends(permission_depends("system:file:main"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def index(request: Request):
    return templates.TemplateResponse("system/photo/photo.html", {"request": request})


#  图片数据
@route.get(
    "/table",
    dependencies=[Depends(permission_depends("system:file:main"))],
    summary="获取图片数据",
    response_model=PageResponse[PhotoSchema],
)
async def table(page: int = 1, limit: int = 10):
    photos = await Photo.all().order_by("-create_time").offset((page - 1) * limit).limit(limit)
    count = await Photo.all().count()

    return table_api(data=photos, count=count)


#   上传
@route.get(
    "/upload",
    dependencies=[Depends(permission_depends("system:file:add"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def upload(request: Request):
    return templates.TemplateResponse("system/photo/photo_add.html", {"request": request})


#   上传接口
@route.post(
    "/upload",
    name="system.adminFile.upload_api",
    dependencies=[Depends(permission_depends("system:file:add"))],
    summary="上传图片",
    response_model=ResultResponse,
)
async def upload_api(file: UploadFile = File(...)):
    # 保存文件到上传目录
    upload_dir = settings.UPLOADED_PHOTOS_DEST
    if not os.path.exists(upload_dir):
        os.makedirs(upload_dir)

    # 生成时间戳文件名
    timestamp = str(int(time.time() * 1000))  # 毫秒级时间戳
    file_extension = os.path.splitext(file.filename)[1] if "." in file.filename else ""
    new_filename = f"{timestamp}{file_extension}"

    # 生成文件路径
    file_path = os.path.join(upload_dir, new_filename)

    # 保存文件
    with open(file_path, "wb") as buffer:
        content = await file.read()
        buffer.write(content)

    # 获取文件大小
    size = os.path.getsize(file_path)

    # 保存到数据库
    photo = Photo(name=new_filename, href=f"/static/upload/{new_filename}", mime=file.content_type, size=str(size))
    await photo.save()

    # res = {"msg": "上传成功", "code": 0, "success": True, "data": {"src": photo.href}}
    return success_api(msg="上传成功", data={"src": photo.href})


#    图片删除
@route.post(
    "/delete",
    dependencies=[Depends(permission_depends("system:file:delete"))],
    summary="删除图片",
    response_model=ResultResponse,
)
async def delete(id: int = Form(...)):
    photo = await Photo.get_or_none(id=id)
    if not photo:
        return fail_api(msg="删除失败")

    # 删除文件
    file_path = os.path.join(settings.UPLOADED_PHOTOS_DEST, photo.name)
    if os.path.exists(file_path):
        os.remove(file_path)

    # 删除数据库记录
    await photo.delete()
    return success_api(msg="删除成功")


# 图片批量删除
@route.post(
    "/batchRemove",
    name="system.adminFile.batch_remove",
    dependencies=[Depends(permission_depends("system:file:delete"))],
    summary="批量删除图片",
    response_model=ResultResponse,
)
@atomic()
async def batch_remove(ids: list[int] = Form(...)):
    photos = await Photo.filter(id__in=ids).all()

    # 删除文件
    for photo in photos:
        file_path = os.path.join(settings.UPLOADED_PHOTOS_DEST, photo.name)
        if os.path.exists(file_path):
            os.remove(file_path)

    # 删除数据库记录
    await Photo.filter(id__in=ids).delete()
    return success_api(msg="删除成功")
